<!--
 * @Description：系统用户管理
 * @author： wlj
 * @date： 2025/04/24 15:28:08
!-->
<template>
  <div class="app-container">
    <div class="user-box">
      <el-card v-if="false" class="ub-left" shadow="never">
        <el-tree
          ref="tree"
          :data="dep_tree_data"
          :props="treeProps"
          accordion
          node-key="no"
          highlight-current
          :default-expanded-keys="[tree_default_check]"
          :default-checked-keys="[tree_default_check]"
          @node-click="handleTreeClick"
        />
      </el-card>
      <el-card class="ub-right" shadow="never">
        <el-form :inline="true" @submit.native.prevent>
          <el-form-item label="组织名称">
            <el-cascader
              v-model="checkedOrg"
              :options="dep_tree_data"
              :props="cascaderProps"
              clearable
              :show-all-levels="false"
              class="sel-input-width"
              @change="handleOrgChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="用户状态">
            <el-select v-model="listQuery.status" clearable placeholder="全部" @change="handleResetPage">
              <el-option v-for="item in global.userStateList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="登录名">
            <el-input v-model="listQuery.loginName" placeholder="请输入登录名，回车搜索" @keyup.enter.native="handleResetPage">
              <el-button slot="append" icon="el-icon-search" @click="handleResetPage"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="listQuery.name" placeholder="请输入姓名，回车搜索" @keyup.enter.native="handleResetPage">
              <el-button slot="append" icon="el-icon-search" @click="handleResetPage"></el-button>
            </el-input>
          </el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form>
        <el-table v-loading="listLoading" :data="tableData" border fit stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" />
          <el-table-column label="ID" prop="id" show-overflow-tooltip width="80" />
          <el-table-column label="组织名称" prop="orgName" show-overflow-tooltip />
          <el-table-column label="登录名" prop="loginName" show-overflow-tooltip />
          <el-table-column label="姓名" prop="name" show-overflow-tooltip />
          <el-table-column label="性别" prop="gender">
            <template slot-scope="scope">
              {{ filterValue(global.userGenderList,scope.row.gender) }}
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="phone" show-overflow-tooltip />
          <el-table-column label="用户类型" prop="type" width="100">
            <template slot-scope="scope">
              {{ filterValue(global.userTypeList,scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column label="账户过期时间" prop="userExpireTime" width="160">
            <template slot-scope="scope">
              {{ scope.row.userExpireTime || '永不过期' }}
            </template>
          </el-table-column>
          <el-table-column prop="forcePasswordChange" label="强制修改默认密码">
            <template slot="header" slot-scope="{}">
              <span>强制修改默认密码</span>
              <el-tooltip class="item" effect="dark" placement="top">
                <i class="el-icon-question" style="font-size: 14px; vertical-align: middle;"></i>
                <div slot="content">
                  <p>新增用户的密码是系统内置密码，此项设置是为用户第一次登录时，是否提示修改使用</p>
                </div>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              {{ scope.row.forcePasswordChange ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column label="用户状态" prop="status">
            <template slot-scope="scope">
              {{ filterValue(global.userStateList,scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip />
          <el-table-column label="备注" prop="remark" show-overflow-tooltip />
          <el-table-column width="100" label="操作" align="center">
            <template v-if="scope.row.status!==3" slot-scope="scope">
              <el-dropdown class="operation-style">
                <span class="el-dropdown-link">  操作<i class="el-icon-arrow-down el-icon--right"></i>  </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="handleRestPwd(scope.row)">重置密码</el-dropdown-item>
                  <el-dropdown-item @click.native="handleSetting(scope.row)">设置过期时间点</el-dropdown-item>
                  <el-dropdown-item @click.native="handleSetLogPlatform(scope.row)">设置可登录平台</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.type!==0" @click.native="handleEdit(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item @click.native="handleChangeState(scope.row)">
                    {{ scope.row.status ===1 ? '封禁':scope.row.status ===2 ?'正常':'' }}
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.type!==0" @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div v-if="count > 0">
          <pagination
            :total="count"
            layout="total,sizes, prev, pager, next, jumper"
            :page.sync="listQuery.page.pageIndex"
            :limit.sync="listQuery.page.pageSize"
            @pagination="search"
          />
        </div>
      </el-card>
    </div>
    <!-- 新增 / 编辑-->
    <el-dialog
      v-loading.fullscreen.lock="fullscreenLoading"
      :title="dialogTitle"
      :visible.sync="isShowDialog"
      form
      width="50%"
      destroy-on-close
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form ref="form" :rules="rules" :model="userForm" label-width="160px" :validate-on-rule-change="false" @submit.native.prevent>
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model.trim="userForm.loginName" :disabled="type==='edit'" placeholder="请输入登录名" autocomplete="on" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="userForm.gender" placeholder="请选择" class="sel-input-width">
            <el-option v-for="item in global.userGenderList" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="type==='add'" label="手机号" prop="phone" :disabled="type==='add'">
          <el-input v-model.trim="userForm.phone" placeholder="请输入手机号码" autocomplete="on" />
        </el-form-item>
        <el-form-item v-if="type!=='edit'" label="管理角色" prop="roleCode">
          <el-select v-model="userForm.roleCode" clearable placeholder="请选择" class="sel-input-width">
            <el-option
              v-for="item in roleList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="type!=='edit'" label="可登录平台" prop="loginPlatform">
          <el-select v-model="userForm.loginPlatform" multiple value-key="value" placeholder="请选择" class="sel-input-width ptf-select">
            <el-option
              v-for="item in global.logPtfList"
              :key="item.value"
              :disabled="item.value==='ADMIN'"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="组织名称" prop="org">
          <el-cascader
            v-model="selectedOrg"
            :options="orgTreeList"
            :props="cascaderProps"
            clearable
            :show-all-levels="false"
            class="sel-input-width"
            @change="handleCascaderChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item v-if="type!=='edit'" label="账户过期时间" prop="userExpireTime">
          <el-date-picker
            v-model.trim="userForm.userExpireTime"
            class="sel-input-width"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            default-time="23:59:59"
            :picker-options="pickerBeginOption"
          ></el-date-picker>
          <div class="tip-text">日期为空，则永不过期</div>
        </el-form-item>
        <!-- <el-form-item v-if="type!=='edit'" label="密码过期时间" prop="passwordExpireTime">
          <el-date-picker
            v-model.trim="userForm.passwordExpireTime"
            class="sel-input-width"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            default-time="23:59:59"
          ></el-date-picker>
        </el-form-item> -->
        <el-form-item v-if="type!=='edit'" label="是否强制修改默认密码" prop="forcePasswordChange">
          <el-radio-group v-model="userForm.forcePasswordChange" v-removeAriaHidden>
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
          <div class="tip-text">新增用户的密码是系统内置密码，此项设置是为用户第一次登录时，是否提示修改使用</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="userForm.remark" type="textarea" :autosize="{ minRows: 2 }" maxlength="300" show-word-limit />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancelDialog()">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置过期时间、可登录平台-->
    <el-dialog
      :title="dialogTimeTitle"
      :visible.sync="isSetTimeDialog"
      form
      width="30%"
      destroy-on-close
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form ref="otherform" :rules="otherRules" :model="otherform" label-width="120px" @submit.native.prevent>
        <el-form-item v-if="type === 'setTime'" label="账户过期时间" prop="expireTime">
          <el-date-picker
            v-model="otherform.expireTime"
            class="sel-input-width"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            default-time="23:59:59"
            :picker-options="pickerBeginOption"
          ></el-date-picker>
          <div class="tip-text">日期为空，则永不过期</div>
        </el-form-item>
        <el-form-item v-if="type==='setPtf'" label="可登录平台" prop="loginPlatform">
          <el-select
            v-model="otherform.loginPlatform"
            multiple
            value-key="value"
            placeholder="请选择"
            class="sel-input-width ptf-select"
          >
            <el-option
              v-for="item in global.logPtfList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleSetCancel()">取 消</el-button>
        <el-button type="primary" @click="handleSetTime('otherform')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findPage, addSystem, editUser, deleteLogicUser, normalUser, bannedUser, setRestUserPwd, settingValidTime, getUserAlLogPlatform, setLogPlatform } from '@/api/basic/sysUser'
import { getRoleList } from '@/api/basic/sysRole'
import { getOrgTree, getRegOrgTree } from '@/api/basic/orgMag'
export default {
  name: 'User',
  data() {
    // 验证手机号
    var ISPhone = /^[1][3,4,5,7,8,9][0-9]{9}$/
    const validatePhone = (rule, value, callback) => {
      if (!ISPhone.test(this.userForm.phone)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      pickerBeginOption: { // 过期时间点--选择时间控制，只能选当前天之后的
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 1 * 24 * 60 * 60 * 1000
        }
      },
      fullscreenLoading: false,
      listLoading: false,
      multipleSelection: [],
      count: 0,
      tableData: [],
      checkedOrg: [],
      listQuery: {
        orgNo: '',
        name: '',
        status: '',
        loginName: '',
        loginPlatform: 'ADMIN',
        page: {
          pageIndex: 1,
          pageSize: 20
        }
      },
      dialogTimeTitle: '',
      isSetTimeDialog: false, // 设置过期时间弹窗
      dialogTitle: '',
      isShowDialog: false, // 新增、编辑弹窗
      userForm: {
        loginName: '',
        gender: '',
        name: '',
        remark: '',
        phone: '',
        userExpireTime: '',
        passwordExpireTime: '',
        forcePasswordChange: true,
        roleCode: '',
        loginPlatform: ['ADMIN'],
        org: {
          // userId: '',
          // orgNo: '',
          // orgName: ''
        }
      },
      rules: {
        loginName: [{ required: true, message: '登录名不能为空', trigger: 'blur' },
          { min: 4, max: 50, message: '登录名长度必须在4-50个字符之间', trigger: 'blur' }],
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        roleCode: [{ required: true, message: '请选择管理角色', trigger: 'blur' }],
        loginPlatform: [{ required: true, message: '请选择可登录的平台', trigger: 'blur' }],
        phone: [{ required: true, message: '手机号码不能为空', trigger: 'blur' },
          { required: true, validator: validatePhone, trigger: 'blur' }]
      },
      type: '', // 类型区分
      otherform: {
        id: '',
        expireTime: '',
        userId: [],
        loginPlatform: [],
        registerPlatform: ''
      },
      otherRules: {
        expireTime: [{ required: false, message: '请选择过期的时间！', trigger: 'blur' }]
      },
      roleList: [], // 管理角色集合
      dep_tree_data: [],
      tree_default_check: '', // 树被选中的数据
      treeProps: {
        label: 'name'
      },
      parentNo: '0',
      selectedOrg: [], // 用于存储选中的值
      orgTreeList: [], // 树形结构数据--// 新增时,组织机构下拉
      cascaderProps: {
        value: 'no', // 指定选项的值为 no 字段
        label: 'name', // 指定选项的标签为 name 字段
        children: 'children', // 指定子节点字段名
        checkStrictly: true // 单选模式
      }
    }
  },
  created() {
    this.initDepTree()
  },
  methods: {
    // 获取树数据--初始化加载--左侧结构树
    initDepTree() {
      getOrgTree(this.parentNo).then((res) => {
        if (res.success) {
          this.dep_tree_data = res.data || []
          this.dep_tree_data.push({ no: '-', name: '其他' })
          if (this.dep_tree_data) {
            this.$nextTick(() => {
              // this.listQuery.orgNo = this.tree_default_check = this.tree_default_check ? this.tree_default_check : 'A'
              // this.$refs.tree.setCurrentKey(this.tree_default_check)
              this.handleResetPage()
            })
          }
        } else this.$message.error(res.message)
      })
    },
    // 树的点击
    handleTreeClick(data, node, dom) {
      // console.log('方法：handleTreeClick，打印：当前点击节点数据', data, '当前点击节点Node', node)
      this.tree_default_check = data.no
      this.listQuery.orgNo = data.no
      // 最后一级也可以点击
      // if (!node.isLeaf) {
      this.handleResetPage()
      // }
    },
    search() {
      this.listLoading = true
      findPage(this.listQuery).then(res => {
        this.tableData = res.data.rows
        this.count = res.data.total
        this.listLoading = false
      })
    },
    // 重置密码
    handleRestPwd(row) {
      this.$confirm('此操作将重置密码, 是否继续?', '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setRestUserPwd({ loginName: row.loginName }).then(res => {
          if (res.success) {
            this.$message({ message: res.message || '重置成功', type: 'success' })
            this.search()
          } else this.$message.error(res.message)
        })
      }).catch(() => {})
    },
    // 单个设置过期时间
    handleSetting(row) {
      this.type = 'setTime'
      this.dialogTimeTitle = '设置过期时间'
      this.isSetTimeDialog = true
      this.otherform.id = row.id
      this.otherform.expireTime = row.userExpireTime
    },
    // 设置可登录平台
    handleSetLogPlatform(row) {
      this.type = 'setPtf'
      this.dialogTimeTitle = '设置可登录平台'
      this.isSetTimeDialog = true
      this.otherform.userId = [row.id]
      this.otherform.registerPlatform = row.registerPlatform
      getUserAlLogPlatform(row.id).then(res => {
        if (res.success) {
          const arr = res.data
          this.otherform.loginPlatform = arr.map(m => { return m.loginPlatform })
        }
      })
    },
    // 弹窗--确定--设置过期时间
    handleSetTime(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return
        if (this.type === 'setTime') {
          settingValidTime({ id: this.otherform.id, expireTime: this.otherform.expireTime }).then(res => {
            if (res.success) {
              this.$message({ message: res.message || '设置成功', type: 'success' })
              this.search()
              this.handleSetCancel()
            }
          })
        }
        if (this.type === 'setPtf') {
          const plf = this.otherform.loginPlatform.length > 0 ? this.otherform.loginPlatform : [this.otherform.registerPlatform]
          setLogPlatform({ userId: this.otherform.userId, loginPlatform: plf }).then(res => {
            if (res.success) {
              this.$message({ message: res.message || '设置成功', type: 'success' })
              this.search()
              this.handleSetCancel()
            }
          })
        }
      })
    },
    // 取消弹窗
    handleSetCancel() {
      this.isSetTimeDialog = false
      this.type = ''
      this.otherform = {
        id: '',
        expireTime: '',
        userId: [],
        loginPlatform: [],
        registerPlatform: ''
      }
    },
    // 获取管理角色集合
    getRole() {
      getRoleList('ADMIN').then(res => {
        if (res.success) {
          this.roleList = res.data
        }
      })
    },
    // 获取可用的树形组织机构
    async getUsableOrgTree() {
      await getRegOrgTree().then(res => {
        if (res.success) {
          this.orgTreeList = res.data
        }
      })
    },
    // 获取选中的组织--对象数据
    handleCascaderChange(value) {
      const len = value.length
      if (len > 0) {
        // 获取选中节点的信息
        const selectedNode = this.findNodeByValue(this.orgTreeList, value[len - 1])
        if (selectedNode) {
          this.userForm.org = {
            userId: '',
            orgNo: selectedNode.no,
            orgName: selectedNode.name
          }
        }
      } else {
        this.userForm.org = { orgNo: '', orgName: '' }
      }
    },
    findNodeByValue(nodes, value) {
      for (const node of nodes) {
        if (node.no === value) {
          return node
        }
        if (node.children) {
          const found = this.findNodeByValue(node.children, value)
          if (found) {
            return found
          }
        }
      }
      return null
    },
    // 新增
    handleAdd() {
      this.type = 'add'
      this.isShowDialog = true
      this.dialogTitle = '新增用户'
      this.getRole()
      this.getUsableOrgTree()
    },
    // 编辑
    async handleEdit(row) {
      await this.getUsableOrgTree()
      this.type = 'edit'
      this.dialogTitle = '编辑用户'
      this.isShowDialog = true
      this.userForm = JSON.parse(JSON.stringify(row))
      if (row.orgNo) {
        this.userForm.org = {
          orgNo: row.orgNo,
          orgName: row.orgName
        }
        this.selectedOrg = this.getParentChild(this.orgTreeList, row.orgNo)
      }
    },
    // 根据集合和最后一级code，获取完整的父子级
    getParentChild(object, value) {
      for (var key in object) {
        if (object[key].no === value) return [object[key].no]
        if (object[key].children && Object.keys(object[key].children).length > 0) {
          var temp = this.getParentChild(object[key].children, value)
          if (temp) return [object[key].no, temp].flat()
        }
      }
    },
    // 提交验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return
        this.handleConfirm()
      })
    },
    // 点击确定新增、编辑
    handleConfirm() {
      this.fullscreenLoading = true
      if (this.type === 'add') {
        addSystem(this.userForm).then(res => {
          if (res.success) {
            this.$message({ message: res.message || '新增成功', type: 'success' })
            this.search()
            this.handleCancelDialog()
            this.fullscreenLoading = false
          }
        }).catch(() => {
          this.fullscreenLoading = false
        })
      } else if (this.type === 'edit') {
        const query = {
          id: this.userForm.id,
          name: this.userForm.name,
          gender: this.userForm.gender,
          remark: this.userForm.remark,
          orgName: this.userForm.org.orgName,
          orgNo: this.userForm.org.orgNo
        }
        editUser(query).then(res => {
          if (res.success) {
            this.$message({ message: res.message || '编辑成功', type: 'success' })
            this.search()
            this.handleCancelDialog()
            this.fullscreenLoading = false
          }
        }).catch(() => {
          this.fullscreenLoading = false
        })
      }
    },
    // 点击 dailog 取消按钮
    handleCancelDialog() {
      this.userForm = {
        loginName: '',
        gender: '',
        name: '',
        remark: '',
        phone: '',
        userExpireTime: '',
        passwordExpireTime: '',
        forcePasswordChange: true,
        roleCode: '',
        loginPlatform: ['ADMIN'],
        org: {}
      }
      this.selectedOrg = []
      this.isShowDialog = false
    },
    // 删除用户(逻辑删除)
    handleDelete(row) { // 单个删除
      this.$confirm('此操作为回收站-逻辑删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLogicUser({ id: row.id }).then(res => {
          if (res.success) {
            this.$message({ message: res.message || '删除成功', type: 'info' })
            this.search()
          } else this.$message.error(res.message)
        })
      }).catch(() => {})
    },
    // 禁用、正常
    handleChangeState(row) {
      const text = row.status === 1 ? '封禁' : row.status === 2 ? '正常' : ''
      this.$confirm('此操作将该用户改为“' + text + '”状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.status === 1) { // 已正常，使其禁用
          this.doStop(row.id)
        } else if (row.status === 2) { // 已禁用，使其正常
          this.doOpen(row.id)
        }
      }).catch(() => {})
    },
    // 执行正常操作
    doOpen(value) {
      normalUser({ id: value }).then(res => {
        if (res.success) {
          this.$message({ message: res.message || '恢复成功', type: 'success' })
          this.search()
        } else this.$message.error(res.message)
      })
    },
    // 执行禁用操作
    doStop(value) {
      bannedUser({ id: value }).then(res => {
        if (res.success) {
          this.$message({ message: res.message || '禁用成功', type: 'info' })
          this.search()
        } else this.$message.error(res.message)
      })
    },
    // 保存多选数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 组织名称-检索条件
    handleOrgChange(value) {
      const len = value.length
      if (len > 0) {
        // 获取选中节点的信息
        const selectedNode = this.findNodeByValue(this.dep_tree_data, value[len - 1])
        if (selectedNode) {
          this.listQuery.orgNo = selectedNode.no
        }
      } else {
        this.listQuery.orgNo = ''
      }

      this.handleResetPage()
    },
    // 切换搜索条件时，页码重置
    handleResetPage() {
      this.listQuery.page.pageIndex = 1
      this.search()
    }
  }
}
</script>
<style lang="scss" scoped>
.tip-text{
  font-size: 12px;
  color: #666;
}
::v-deep{
 .ptf-select{
   .el-select__tags .el-tag .el-tag__close.el-icon-close {
      display: none !important;
    }
  }
}
.user-box{
  display: flex;
  .ub-left{
    width:320px;
    min-height: 720px;
    margin-right: 20px;
  }
  .ub-right{
    flex: 1;
  }
}

</style>
